<?php defined('SYSPATH') or die('No direct script access.');

 class Controller_Post extends Controller_Base{

    //详情页
    public function action_index(){

      $id=$this->request->param("id")?$this->request->param("id"):$this->request->post("id");

      if(empty($id)){

        if($this->request-> is_ajax()){

          $result=array();

          $result['code']='0x00001';

          exit(json_encode($result));

        }
        else{

          $this->redirect("/");

        }
      }

      $model_post=new Model_Post();

      $post=$model_post->getPostById($id);

      if(empty($post)){

        if($this->request-> is_ajax()){

            $result=array();

            $result['code']='0x00001';

            exit(json_encode($result));
        }
        else{

          $this->redirect("/");

        }
      }
      else{

          $model_review=new Model_Review();

          $post_review=$model_review->getInfo($id,0,10);

          if($this->request-> is_ajax()){

            $result=array();

            $result['code']='0x00000';

            if(Lib_Base::is_mobile()){

               $view=View::factory('mobile/post/detail');

            }
            else{

              $view=View::factory('post/block/detail');

            }

            $view->post=$post;

            $view->post_review=$post_review;

            $result['data']=$view->render();

            exit(json_encode($result));
          }
          else{

              $this->template->title = __($post['title']);

              if(Lib_Base::is_mobile()){

                $view=View::factory('mobile/post/detail');

              }
              else{

                $view=View::factory('post/index');

              }

              $view->post=$post;

              $view->post_review=$post_review;

              $this->template->content =$view;

          }
      }

    }
    //加载post
    public function action_load(){

      $user=Session::instance()->get('user');

      $result=array();

      if(!empty($user)){

        $userid=$user['userid'];

        $cache = Cache::instance();

        $id=$this->request->post("id");

        $model_album=new Model_Album();

        $data=array();

        $tags = $cache->get('site_tags',NULL);

        if(empty($tags)){

           $tags=DB::select(array('tagid','id'),'caption')
           
           ->from('tag')->order_by('createdon', 'desc')->limit(20)->execute()->as_array();
        }

        $data['tags']=$tags;

        $result['code']='0x00000';

        if(!empty($id)){

          $model_post=new Model_Post();

          $data['post']=$model_post->getUserPost($userid,$id);

        }

        $c_cache= Cache::instance();

        //获取分类信息
        $category= $c_cache->get('site_category',NULL);

        if(empty($category)){

             $sql="select t.assortid id,t.caption,t.url
             from assort t
             where t.isdeleted<>'1'
             order by t.createdon desc";

            $category=DB::query(Database::SELECT,$sql)->execute()->as_array();

            $c_cache->set('site_category',$category,30000);
        }

        $data['assort']=$category;

        $result['data']=Block_Post::load($data);

      }
      else{

        $result['code']='0x00001';

      }

      exit(json_encode($result));
    }

    public function action_saveinfo(){

      $user=Session::instance()->get('user');

      if(!empty($user)){

        $userid=$user['userid'];

        $id=$this->request->post("id");

        $img_info=trim($this->request->post("img_info"));

        $title=trim($this->request->post("title"));

        $introduction=trim($this->request->post("introduction"));

        $description=trim($this->request->post("description"));

        $tags=trim($this->request->post("tags"));

        $assort=trim($this->request->post("assort"));

        $type=trim($this->request->post("type"));

        $url=trim($this->request->post("url"));

        if(empty($id)){

          exit($this->add($userid,$img_info,$title,$introduction,$description,$tags,$assort,$type,$url));
            
        }
        else{

          exit($this->alter($id,$userid,$img_info,$title,$introduction,$description,$tags,$assort,$type,$url));
          
        }
        
      }
      else{

        $result=array();

        $result['code']='0x00001';

        exit(json_encode($result));

      }

    }

    private function add($userid,$img_info,$title,$introduction,$description,$tags,$assort,$type,$url){

        try{

          $img_info_arr =explode(";", trim($img_info));

          $main_image="";

          $images="";

          $count=count($img_info_arr);

          foreach ($img_info_arr as $i => $image) {

            if($i==$count-1){

              $images=$images.$image;

            }
            else{

              $images=$images.$image.";";

            }
            
          }

          Database::instance()->begin();

          list($insert_id, $total_rows)= DB::insert('post')

          ->columns(array('userid','title','introduction','description','tags','created','images','assort','type','url'))
              
          ->values(array($userid,$title,$introduction,$description,$tags,date("Y-m-d h:i:sa"),$images,$assort,$type,$url))->execute();

           foreach ($img_info_arr as $i => $image) {

              $oldFile='temp/t/'.$image;

              if(file_exists($oldFile)){

                $newFile='temp/post/post'.$insert_id."-M-".$image;

                copy($oldFile,$newFile);

                $img = Image::factory($newFile);

                $filename ='temp/post/post'.$insert_id."-M500-".$image;

                $img->resize(500, NULL)->save($filename);

                $filename ='temp/post/post'.$insert_id."-M260-".$image;

                $img->resize(260, NULL)->save($filename);

                $filename ='temp/post/post'.$insert_id."-M100-".$image;

                $img->resize(100, NULL)->save($filename);

                unlink($oldFile);

              }
              
          }

          Database::instance()->commit();

          $user=Session::instance()->get('user');

          $post_list=array();

          $post_list[]=array(
            'id'=>$insert_id,
            'title'=>$title,
            'introduction'=>$introduction,
            'description'=>$description,
            'images'=>$images
          );

          $post_info=Block_User::post_list($user,$post_list);

          return json_encode(array("code"=>"0x00000",'id'=>$insert_id,'title'=>$title,'post_info'=>$post_info));

        }
        catch (Exception $e) {

          Database::instance()->rollback();

          return json_encode(array("info"=>"上传失败","code"=>"0x0000x"));
        }

    }

    private function alter($id,$userid,$img_info,$title,$introduction,$description,$tags,$assort,$type,$url){

      try{

         $img_info_arr =explode(";", trim($img_info));

          $count=count($img_info_arr);

          $images="";

          foreach ($img_info_arr as $i => $image) {

            if($i==$count-1){

              $images=$images.$image;

            }
            else{

              $images=$images.$image.";";

            }
            
          }

          Database::instance()->begin();

          $total_rows=DB::update('post')
            ->set(array('title'=>$title,
                'introduction'=>$introduction,
                'description'=>$description,
                'images'=>$images,
                'tags'=>$tags,
                'assort'=>$assort,
                'type'=>$type,
                'url'=>$url
                ))
            ->where('postid','=',$id)
            ->and_where('userid','=',$userid)
            ->execute();

          foreach ($img_info_arr as $i => $image) {

              $oldFile='temp/t/'.$image;

              $ci='temp/post/post'.$id."-M-".$image;

              if(!file_exists($ci)){

                if(file_exists($oldFile)){

                  copy($oldFile,$ci);

                  $img = Image::factory($ci);

                  $filename ='temp/post/post'.$id."-M500-".$image;

                  $img->resize(500, NULL)->save($filename);

                  $filename ='temp/post/post'.$id."-M260-".$image;

                  $img->resize(260, NULL)->save($filename);

                  $filename ='temp/post/post'.$id."-M100-".$image;

                  $img->resize(100, NULL)->save($filename);

                  unlink($oldFile);

                }

              }
              else{

                  $filename ='temp/post/post'.$id."-M500-".$image;

                  $img = Image::factory($ci);

                  if(!file_exists($filename)){

                    $img->resize(500, NULL)->save($filename);

                  }

                  $filename ='temp/post/post'.$id."-M260-".$image;

                  if(!file_exists($filename)){

                    $img->resize(260, NULL)->save($filename);
                    
                  }
                
                  $filename ='temp/post/post'.$id."-M100-".$image;

                  if(!file_exists($filename)){

                    $img->resize(100, NULL)->save($filename);
                    
                  }
                  
              }
          }

          Database::instance()->commit();

          $post_list=array(
            'id'=>$id,
            'title'=>$title,
            'introduction'=>$introduction,
            'description'=>$description,
            'image'=>Lib_Image::getPostImage($id,$images,260)
          );

          return json_encode(array("code"=>"0x00000",'id'=>$id,'title'=>$title,'post_list'=>$post_list));

      }
      catch (Exception $e) {

        Database::instance()->rollback();

        return json_encode(array("info"=>"上传失败","code"=>"0x0000x"));
      } 
        
    }

    public function action_interact(){

      $result=array();

      $post_id=$this->request->post("id");

      $t=$this->request->post("t");

      if(empty($post_id)||empty($t)){

        $result['code']='0x0000x';

        exit(json_encode($result));

      }

      $user=Session::instance()->get('user');

      $userid=!empty($user)?$user['userid']:"";

      if($t=="praiseup"){

        exit($this->praiseup($userid,$post_id));
                 
      }

    }

    private function praiseup($userid,$post_id){

      $result=array();

      try {

        Database::instance()->begin();

        if(empty($userid)){

          $cookie_praiseup=Cookie::get('praiseup_'.$post_id);

          if(empty($cookie_praiseup)){

            DB::update('post')->set(array('praiseup' => DB::expr("praiseup + 1")))->where('postid', '=', $post_id)->execute();

            Cookie::set('praiseup_'.$post_id,'1');

            $result['code']="0x00000";

          }

          else{

              DB::update('post')->set(array('praiseup' => DB::expr("praiseup - 1")))->where('postid', '=', $post_id)->and_where("praiseup",">","0")->execute();

              Cookie::set('praiseup_'.$post_id,'');

              $result['code']="0x00003";

          }

        }
        else{

          $c= DB::select(array('interactid', 'id'))

          ->from('interact')

          ->where("postid",'=',$post_id)

          ->and_where("userid",'=',$userid)

          ->and_where("type",'=',"praiseup")

          ->limit(1)

          ->execute()

          ->get('id');

          if(empty($c)){

            list($insert_id, $total_rows)= DB::insert('interact')

            ->columns(array('userid','postid','type','createdon'))
              
            ->values(array($userid,$post_id,'praiseup',date("Y-m-d h:i:sa")))->execute();

            DB::update('post')->set(array('praiseup' => DB::expr("praiseup+1")))->where('postid', '=', $post_id)->execute();

            Cookie::set('praiseup_'.$userid."_".$post_id,'1');

            $result['code']='0x00000';
      
          }
          else{

            DB::delete('interact')->where('postid', '=', $post_id)->and_where('type','=','praiseup')->and_where("userid","=",$userid)->execute();

            DB::update('post')->set(array('praiseup' => DB::expr("praiseup-1")))->where('postid', '=', $post_id)->and_where("praiseup",">","0")->execute();

            Cookie::set('praiseup_'.$userid."_".$post_id,'');

            $result['code']="0x00003";
          
          }
        }

        Database::instance()->commit();

      }
      catch (Exception $e) {

        $result['code']="0x0000x";

        Database::instance()->rollback();

      }  

      return json_encode($result);

    }

    public function action_remove(){

      $id=$this->request->post("id");

      $user=Session::instance()->get('user');

      $result=array();

      if(!empty($user)){

        $userid=$user["userid"];

        $model=new Model_Post();

        $result=$model->remove($userid,$id);

      }
      else{

        $result['code']='0x00001';

      }

      exit(json_encode($result));
    }

    public function action_updateView(){

      $id=$this->request->post("id");

      if(empty($id)){

        exit(json_encode(array("code"=>"0x0000x")));

      }

      try {

        Database::instance()->begin();

        DB::update('post')->set(array('view' => DB::expr('view + 1')))->where('postid', '=', $id)->execute();

        Database::instance()->commit();

        exit(json_encode(array("code"=>"0x00000")));

      }
      catch (Exception $e) {

        Database::instance()->rollback();

        exit(json_encode(array("code"=>"0x0000x")));

      }
    }

 } 
